package pers.amos.edu.service;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import pers.amos.edu.common.RedisKeyConstant;
import pers.amos.edu.pojo.SchoolMajor;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

/**
 * @author amos wong
 * @create 2020-02-01 19:09
 */

@Service
public class SchoolMajorService {

    @Autowired
    private RedisTemplate redisTemplate;

    public List<SchoolMajor> getMajorBySchoolId(Integer id, String openId) {
        List<LinkedHashMap<String, Object>> majorMapList = redisTemplate.opsForList().range(RedisKeyConstant.SCHOOL_MAJOR_KEY + id, 0, -1);
        List<SchoolMajor> schoolMajorList = new ArrayList<>();
        majorMapList.forEach(majorMap -> {
            SchoolMajor schoolMajor = new SchoolMajor();
            Integer schoolId = (Integer) majorMap.get("schoolId");
            String schoolName = (String) majorMap.get("schoolName");
            String level = (String) majorMap.get("level");
            String majorName = (String) majorMap.get("majorName");
            String requirement = (String) majorMap.get("requirement");
            String fields = (String) majorMap.get("fields");
            schoolMajor.setSchoolId(schoolId);
            schoolMajor.setSchoolName(schoolName);
            schoolMajor.setLevel(level);
            schoolMajor.setMajorName(majorName);
            schoolMajor.setRequirement(requirement);
            schoolMajor.setFields(fields);
            if (StringUtils.isNotEmpty(openId)) {
                Boolean isMember = redisTemplate.opsForSet().isMember(RedisKeyConstant.USER_COLLECT_MAJOR_KEY + openId, majorName);
                if (isMember) {
                    schoolMajor.setCollectionStatus(1);
                }
            }
            schoolMajorList.add(schoolMajor);
        });
        return schoolMajorList;
    }
}
